<template>
  <div class="com-container">
    <div class="com-echart" ref="hot_ref"></div>
    <span class="iconfont arr-left" @click="toLeft" :style="comStyle"
      >&#xe6ef;</span
    >
    <span class="iconfont arr-right" @click="toRight" :style="comStyle"
      >&#xe6ed;</span
    >
    <span class="cat-name">{{ catName }}</span>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { getThemeValue } from '@/utils/theme_utils';
export default {
  data() {
    return {
      echartInstance: null,
      // 服务器返回的数据
      allData: null,
      //   当前所展示的一级分类数据
      currentIndex: 0,
      titleFontSize: 0
    };
  },
  computed: {
    catName() {
      return this.allData ? this.allData[this.currentIndex].name : '';
    },
    comStyle() {
      return {
        fontSize: this.titleFontSize + "px",
        color: getThemeValue(this.theme).titleColor
      };
    },
    ...mapState(['theme']),
  },
  watch:{
    theme(){
      // 销毁当前图表
      this.echartInstance.dispose();
      this.initChart();
      this.screenAdapter();
      this.updateChart();
    }
  },
  mounted() {
    this.initChart();
    this.getData();
    window.addEventListener("resize", this.screenAdapter);
    // 首次适配
    this.screenAdapter();
  },
  beforeDestroy() {
    // 移除resize事件
    window.removeEventListener("resize", this.screenAdapter);
  },
  methods: {
    // 初始化echartsInstance对象
    initChart() {
      this.echartInstance = this.$echarts.init(this.$refs.hot_ref, this.theme);
      // 对图表初始化配置的控制
      const initOption = {
        title: {
          text: "▎热销商品的占比",
          left: 20,
          top: 20
        },
        legend: {
          top: "15%",
          icon: "circle"
        },
        tooltip: {
          show: true,
          formatter: arg => {
            // console.log('arg:',arg);
            const thirdCategory = arg.data.children;
            let total = 0;
            thirdCategory.forEach(v => {
              total += v.value;
            });
            let retStr = "";
            thirdCategory.forEach(v => {
              retStr += `
                ${v.name}: ${parseInt((v.value / total) * 100) + "%"}
                <br/>
                `;
            });
            return retStr;
          }
        },
        series: [
          {
            type: "pie",
            label: {
              show: false
            },
            // 鼠标悬停高亮显示
            emphasis: {
              // 表示显示label
              label: {
                show: true
              },
              // label线隐藏
              labelLine: {
                show: false
              }
            }
          }
        ]
      };
      this.echartInstance.setOption(initOption);
    },
    // 获取服务器数据
    async getData() {
      const { data: ret } = await this.$http.get("hot");
      this.allData = ret;

      this.updateChart();
    },
    // 更新图表
    updateChart() {
      const legendData = this.allData[this.currentIndex].children.map(
        v => v.name
      );
      const seriesData = this.allData[this.currentIndex].children.map(v => {
        return {
          name: v.name,
          value: v.value,
          // 此项数据是为了在tooltip中显示
          children: v.children
        };
      });
      const dataOption = {
        legend: {
          data: legendData
        },
        series: [
          {
            data: seriesData
          }
        ]
      };
      this.echartInstance.setOption(dataOption);
    },
    // 图表对屏幕的适配
    screenAdapter() {
      this.titleFontSize = (this.$refs.hot_ref.offsetWidth / 100) * 3.6;
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: this.titleFontSize
          }
        },
        legend: {
          itemWidth: this.titleFontSize,
          itemHeight: this.titleFontSize,
          //   图例与图例的间隔
          itemGap: this.titleFontSize / 2,
          textStyle: {
            fontSize: this.titleFontSize / 2
          }
        },
        series: [
          {
            radius: this.titleFontSize * 4.5,
            center: ["50%", "60%"]
          }
        ]
      };
      this.echartInstance.setOption(adapterOption);
      // 手动调用图表对象的resize以适配
      this.echartInstance.resize();
    },
    toLeft() {
      this.currentIndex--;
      if (this.currentIndex < 0) {
        // 会到最后的索引
        this.currentIndex = this.allData.length - 1;
      }
      this.updateChart();
    },
    toRight() {
      this.currentIndex++;
      // 比最后索引大，则设置为0
      if (this.currentIndex > this.allData.length - 1) {
        this.currentIndex = 0;
      }
      this.updateChart();
    }
  }
};
</script>

<style lang="less" scoped>
.arr-left {
  position: absolute;
  left: 10%;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: white;
}
.arr-right {
  position: absolute;
  right: 10%;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: white;
}
.cat-name {
  position: absolute;
  left: 80%;
  bottom: 20px;
  color: white;
}
</style>
